<template>
  <div class="page-prod-manage">
    <!-- 表单 -->
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
      >
        <div class="input-row">
          <el-form-item :label="$t('product.prodName') + ':'">
            <el-input
              v-model="prodName"
              type="text"
              :placeholder="$t('product.prodName')"
            />
          </el-form-item>
          <!-- 商品类别 -->
          <el-form-item
            prop="isCompose"
            :label="$t('product.prodTypes') + ':'"
          >
            <el-select
              v-model="searchForm.isCompose"
              :placeholder="$t('product.prodTypes')"
            >
              <el-option
                :label="$t('product.ordProd')"
                :value="0"
              />
              <el-option
                :label="$t('product.comProd')"
                :value="1"
              />
            </el-select>
          </el-form-item>
          <!-- 商品类型 -->
          <el-form-item
            prop="prodType"
            :label="$t('product.prodType') + ':'"
          >
            <el-select
              v-model="searchForm.prodType"
              :placeholder="$t('product.prodType')"
            >
              <el-option
                :label="$t('product.ordProd')"
                :value="0"
              />
              <el-option
                :label="$t('product.groupingProd')"
                :value="1"
              />
              <el-option
                :label="$t('product.spikeProd')"
                :value="2"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="status"
            :label="$t('product.status') + ':'"
          >
            <el-select
              v-model="searchForm.status"
              :placeholder="$t('product.status')"
            >
              <el-option
                :label="$t('publics.UpperShelf')"
                :value="1"
              />
              <el-option
                :label="$t('publics.LowerShelf')"
                :value="0"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="deliveryMode"
            :label="$t('product.delType') + ':'"
          >
            <el-select
              v-model="searchForm.deliveryMode"
              :placeholder="$t('product.delType')"
            >
              <el-option
                :label="$t('product.userPickUp')"
                :value="0"
              />
              <el-option
                :label="$t('order.ordinaryExpress')"
                :value="1"
              />
              <el-option
                :label="$t('product.sameCityDelivery')"
                :value="2"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="isStockWarning"
            :label="$t('product.stockWarning') + ':'"
          >
            <el-select
              v-model="searchForm.isStockWarning"
              :placeholder="$t('product.stockWarning')"
            >
              <el-option
                :label="$t('product.yes')"
                :value="1"
              />
              <el-option
                :label="$t('product.no')"
                :value="0"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <!-- 主体内容 -->
    <div class="main-container">
      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-checkbox
          v-model="selectAll"
          :disabled="!dataList.length"
          class="all-check-btn"
          @change="onSelectAll"
        >
          {{ $t('publics.selectAll') }}
        </el-checkbox>
        <div
          v-if="dataListSelections.length"
          class="had-selected"
        >
          {{ $t('brand.selected') }} {{ dataListSelections.length }}
        </div>
        <div
          v-if="isAuth('prod:prod:save')"
          class="default-btn primary-btn"
          @click.stop="onAddOrUpdate(null)"
        >
          {{ $t('product.addNew') }}
        </div>
        <div
          v-if="isAuth('prod:prod:save')"
          class="default-btn primary-btn"
          @click.stop="onAddComposeProd"
        >
          {{ $t('product.addNewCombinationGoods') }}
          <el-tooltip :content="$t('product.addCombinedProdTip')">
            <el-icon>
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </div>
        <div
          class="default-btn"
          @click="getExportExcel"
        >
          {{ $t('formData.export') }}
        </div>
        <div
          class="default-btn"
          @click.stop="onImportPord"
        >
          {{ $t('product.importGoods') }}
        </div>
        <div
          class="batch-setting-con"
          @click="showBatchSetting = true"
        >
          <el-dropdown
            :hide-on-click="false"
            trigger="click"
            @command="onBatchSetting"
            @visible-change="handleVisibleChange"
          >
            <div :class="[showBatchSetting ? 'active' : '', 'default-btn']">
              {{ $t('publics.batchSetting') }}
              <el-icon class="el-icon--right">
                <ArrowDown />
              </el-icon>
            </div>
            <template #dropdown>
              <!-- 批量设置功能列表 -->
              <el-dropdown-menu>
                <el-dropdown-item command="1">
                  {{ $t('product.batchUp') }}
                </el-dropdown-item>
                <el-dropdown-item command="0">
                  {{ $t('product.batchDown') }}
                </el-dropdown-item>
                <el-dropdown-item command="-1">
                  {{ $t('publics.batchDelete') }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <!-- 表格 -->
      <div
        ref="closepopoverRef"
        class="table-con prod-table"
      >
        <el-table
          :key="tableKey"
          ref="tableRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
          @selection-change="onSelectSome"
          @cell-mouse-enter="enterTableRow"
          @cell-mouse-leave="leaveTableRow"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            fixed
            align="left"
            prop="prodName"
            :label="$t('product.prodInfo')"
            width="320"
          >
            <template #default="scope">
              <div class="table-cell-con">
                <div class="table-cell-image">
                  <ImgShow :src="scope.row.pic" />
                </div>
                <span class="table-cell-text">{{ scope.row.prodName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="left"
            prop="oriPrice"
            :label="$t('prodList.marketValue')"
            width="150"
            sortable
          />
          <el-table-column
            align="left"
            prop="price"
            :label="$t('prodList.salesPrice')"
            width="130"
            sortable
          />
          <el-table-column
            align="left"
            prop="totalStocks"
            :label="$t('product.availableInventory')"
            width="130"
            sortable
          />
          <el-table-column
            :align="'center'"
            :label="$t('product.waterSoldNum')"
            width="150"
          >
            <template #default="scope">
              <div class="water-sold-con">
                <span>{{ scope.row.waterSoldNum }}</span>
                <el-popover
                  width="auto"
                  placement="bottom"
                  trigger="click"
                  @after-enter=" getCurrentSpuId(scope.row.prodId, 'waterSoldNum', scope.row.waterSoldNum) "
                  @hide="initProdInf()"
                >
                  <template #reference>
                    <el-icon
                      v-show="
                        currentMoveProdId === scope.row.prodId ||
                          (scope.row.prodId === currentClickProdId &&
                            currentShowPopover === 'waterSoldNum')
                      "
                    >
                      <Edit />
                    </el-icon>
                  </template>
                  <div class="popover-box">
                    <el-input-number
                      v-model="currentClickWaterSoldNum"
                      type="number"
                      :min="0"
                      :max="1000000000"
                      @keyup.enter="onChangeWaterSoldNum(scope.row.prodId, currentClickWaterSoldNum)"
                    />
                    <div class="popover-bottom">
                      <el-button
                        size="small"
                        @click="closePopover()"
                      >
                        {{ $t('crud.cancelBtn') }}
                      </el-button>
                      <el-button
                        size="small"
                        type="primary"
                        @click="onChangeWaterSoldNum(scope.row.prodId, currentClickWaterSoldNum)"
                      >
                        {{ $t('crud.saveBtn') }}
                      </el-button>
                    </div>
                  </div>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <!-- 商品类别 -->
          <el-table-column
            align="center"
            prop="isCompose"
            :label="$t('product.prodTypes')"
            width="130"
          >
            <template #default="scope">
              <div class="tag-text">
                {{ [$t('product.ordProd'), $t('product.comProd')][scope.row.isCompose] }}
              </div>
            </template>
          </el-table-column>
          <!-- 商品类型 -->
          <el-table-column
            align="center"
            prop="prodType"
            :label="$t('product.prodType')"
            width="130"
          >
            <template #default="scope">
              <div class="tag-text">
                {{ shopProdTypeArr[scope.row.prodType] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="status"
            :label="$t('product.status')"
            width="130"
            sortable
          >
            <template #default="scope">
              <div
                v-if="scope.row.status === 1"
                class="tag-text"
              >
                {{ $t('publics.UpperShelf') }}
              </div>
              <div
                v-if="scope.row.status === 0"
                class="tag-text"
              >
                {{ $t('publics.LowerShelf') }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="deliveryMode"
            :label="$t('product.delType')"
            min-width="130"
          />
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="200"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('prod:prod:update')"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.prodId)"
                >
                  {{ $t('groups.edit') }}
                </div>
                <div
                  v-if="isAuth('prod:prod:update') && scope.row.status === 0"
                  class="default-btn text-btn"
                  @click="onChangeProdStatus(scope.row.prodId, 1)"
                >
                  {{ $t('publics.UpperShelf') }}
                </div>
                <div
                  v-if="isAuth('prod:prod:update') && scope.row.status === 1"
                  class="default-btn text-btn"
                  @click="onChangeProdStatus(scope.row.prodId, 0)"
                >
                  {{ $t('publics.LowerShelf') }}
                </div>
                <div
                  v-if="isAuth('prod:prod:delete')"
                  class="default-btn text-btn"
                  @click="onDelete(scope.row.prodId)"
                >
                  {{ $t('text.delBtn') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @update:page-size="onPageSizeChange"
        @update:current-page="onPageChange"
      />
    </div>
    <!-- 上传文件 -->
    <ProdImport
      v-if="prodImportVisible"
      ref="prodImportRef"
      @input-callback="getWaitingConsignmentExcel"
    />
  </div>
</template>

<script setup>
import ProdImport from './components/prod-import.vue'
import { isAuth } from '@/utils'
import { QuestionFilled, ArrowDown, Edit } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 保存上次点击查询的请求条件
let tempSearchForm = null

// 表单数据
const searchForm = reactive({
  deliveryMode: '',
  isCompose: '',
  status: '',
  prodType: '',
  isStockWarning: ''
})

const dataList = ref([])
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const prodId = ref(null)
const prodNameRoute = ref('')
const prodName = ref('')
const tableKey = ref(Math.random())
/**
 * 获取列表
 * @param {Object} pageParams 分页参数
 * @param {Boolean} newData 是否是新的查询条件
 */
const getDataList = (pageParams, newData = false) => {
  if (page) {
    const size = Math.ceil(page.total / page.pageSize)
    page.currentPage = page.currentPage > size ? size : page.currentPage
  }
  if (newData || !tempSearchForm) {
    const temp = JSON.parse(JSON.stringify(searchForm))
    tempSearchForm = {
      ...temp,
      prodName: prodNameRoute.value ? prodNameRoute.value : prodName.value,
      isStockWarning: (searchForm.isStockWarning || searchForm.isStockWarning === 0) ? searchForm.isStockWarning : '',
      prodId: prodId.value ? prodId.value : null
    }
  }
  http({
    url: http.adornUrl('/prod/prod/page'),
    method: 'get',
    params: http.adornParams(Object.assign(tempSearchForm, {
      current: pageParams == null ? page.currentPage : pageParams.currentPage,
      size: pageParams == null ? page.pageSize : pageParams.pageSize
    }))
  }).then(({ data }) => {
    dataList.value = data.records
    for (const key in dataList.value) {
      if (Object.prototype.hasOwnProperty.call(dataList.value, key)) {
        const element = dataList.value[key]
        if (element.imgs) {
          element.imgs = element.imgs.split(',')[0]
        }
      }
    }
    page.total = data.total
    page.currentPage = data.current ? data.current : 1
    prodNameRoute.value = null
    tableKey.value = Math.random()
    tableRef.value?.clearSelection()
  })
}
onMounted(() => {
  prodNameRoute.value = route.query.prodName || ''
  if (route.query.isStockWarning) {
    searchForm.isStockWarning = Number(route.query.isStockWarning)
  }
  prodId.value = route.query.prodId ? route.query.prodId : null
  getDataList()
})

const onPageSizeChange = val => {
  page.pageSize = val
  getDataList()
}
const onPageChange = val => {
  page.currentPage = val
  getDataList()
}

// 移入项的spuId
const currentMoveProdId = ref('')

// 移入表格行
const enterTableRow = row => {
  currentMoveProdId.value = row.prodId
}
// 移出表格行
const leaveTableRow = () => {
  currentMoveProdId.value = ''
}

// 点击项的spuId
const currentClickProdId = ref('')
// 当前展示的弹窗
const currentShowPopover = ref('')
// 当前展示弹窗 数值
const currentClickWaterSoldNum = ref(0)

// 获取弹出弹窗项信息
const getCurrentSpuId = (spuId, showPopover, waterSoldNum) => {
  currentClickProdId.value = spuId
  currentShowPopover.value = showPopover
  currentClickWaterSoldNum.value = waterSoldNum
}
// 清空选中项弹窗信息
const onClearShowPopoverInfo = () => {
  currentClickProdId.value = ''
  currentShowPopover.value = ''
  currentClickWaterSoldNum.value = 0
}
// 关闭弹窗后,初始化数据
const initProdInf = () => {
  onClearShowPopoverInfo()
}
const closepopoverRef = ref()
// 关闭弹窗
const closePopover = () => {
  closepopoverRef.value.click()
}

// 更改注水销量
const onChangeWaterSoldNum = (id, waterSoldNum) => {
  waterSoldNum = Math.round(waterSoldNum)
  if (waterSoldNum > 1000000000) {
    waterSoldNum = 1000000000
  }
  http({
    url: http.adornUrl('/prod/prod/waterSoldNum'),
    method: 'put',
    params: {
      waterSoldNum,
      prodId: id
    }
  }).then(() => {
    closePopover()
    ElMessage({
      message: '操作成功',
      type: 'success',
      duration: 1500
    })
    getDataList(page)
  })
}
const commonStore = useCommonStore()
// 编辑/新增
const onAddOrUpdate = prodId => {
  /* 判断是否拥有权限 */
  const routeList = commonStore.routeList
  const flag = routeList.some(item => item.url === 'prod/prod/add-or-update')
  if (!flag) {
    ElMessage({
      message: '您暂时没有权限访问',
      type: 'error',
      duration: 1500
    })
    return
  }
  let query = {}
  prodId && (query = { prodId })
  router.push({
    path: '/prod/prod/add-or-update',
    query
  })
}

// 改变状态
const onChangeProdStatus = (id, status) => {
  ElMessageBox.confirm(
    `${$t('sys.makeSure')}${status ? $t('publics.UpperShelf') : $t('publics.LowerShelf')}${$t(
      'text.menu'
    )}?`,
    $t('text.tips'),
    {
      confirmButtonText: $t('crud.filter.submitBtn'),
      cancelButtonText: $t('crud.filter.cancelBtn'),
      type: 'warning'
    }
  ).then(() => {
    http({
      url: http.adornUrl('/prod/prod/prodStatus'),
      method: 'put',
      data: http.adornData({
        status,
        prodId: id
      })
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          getDataList(page)
        }
      })
    })
  })
}

const dataListSelections = ref([])
// 删除商品
const onDelete = id => {
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.prodId
  })
  ElMessageBox.confirm(`${$t('admin.isDeleOper')}`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl(`/prod/prod/${id}`),
      method: 'delete',
      data: http.adornData({})
    }).then(() => {
      page.total = page.total - ids.length
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          getDataList(page)
        }
      })
    })
  })
}

const showBatchSetting = ref(false)

// 新增组合商品 prodId
const onAddComposeProd = () => {
  router.push({
    path: '/prod/prod/add-or-update',
    query: { isCompose: 1 }
  })
}
// 导出按钮
const getExportExcel = () => {
  ElMessageBox.confirm(`${$t('product.exportProd')}`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/prod/prod/exportProd'),
      method: 'get',
      params: http.adornParams(
        Object.assign(
          {
            prodName: prodNameRoute.value ? prodNameRoute.value : prodName.value,
            prodId: prodId.value ? prodId.value : null
          },
          searchForm
        )
      ),
      responseType: 'blob' // 解决文件下载乱码问题
    }).then(({ data }) => {
      const blob = new Blob([data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
      })
      const fileName = $t('product.comInfoSorXls')
      const elink = document.createElement('a')
      if ('download' in elink) {
        // 非IE下载
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    })
  })
}

// 导入商品
const prodImportVisible = ref(false)
const prodImportRef = ref()
const onImportPord = () => {
  prodImportVisible.value = true
  nextTick(() => {
    prodImportRef.value.init()
  })
}

const tableRef = ref()
const selectAll = ref(false)
/**
 * 全选按钮
 */
const onSelectAll = () => {
  selectAll.value = tableRef.value.getSelectionRows().length < dataList.value.length
  tableRef.value.toggleAllSelection()
}

// 多选变化
const onSelectSome = val => {
  dataListSelections.value = val
  selectAll.value = val.length === dataList.value.length && dataList.value.length > 0
}

/**
 * 批量设置菜单显隐
 */
const handleVisibleChange = val => {
  showBatchSetting.value = val
}

/**
 * 批量设置
 */
const onBatchSetting = command => {
  const commands = Number(command)
  if (!dataListSelections.value.length) {
    ElMessage.warning($t('marketing.pleaseSelectAProduct'))
    return
  }
  if (commands !== -1) {
    onBatchChangeProdStatus(commands)
  } else {
    batchDeleteHandle()
  }
}
// 批量改变状态
const onBatchChangeProdStatus = status => {
  const prodList = dataListSelections.value.filter(item => {
    // 相同状态不再改变
    return item.status !== status
  })
  const ids = prodList.map(item => {
    return item.prodId
  })
  ElMessageBox.confirm(
    `${$t('sys.makeSure')}【${status ? $t('product.batchUp') : $t('product.batchDown')}】${$t(
      'publics.operating'
    )}?`,
    $t('text.tips'),
    {
      confirmButtonText: $t('crud.filter.submitBtn'),
      cancelButtonText: $t('crud.filter.cancelBtn'),
      type: 'warning'
    }
  ).then(() => {
    http({
      url: http.adornUrl('/prod/prod/batchProdStatus/' + status),
      method: 'put',
      data: http.adornData(ids, false)
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          refreshChange()
        }
      })
    })
  })
}

// 批量删除
const batchDeleteHandle = () => {
  const ids = dataListSelections.value.map(item => {
    return item.prodId
  })
  ElMessageBox.confirm(
    `${$t('sys.makeSure')}【${$t('sys.batchDelete')}】${$t('publics.operating')}?`,
    $t('text.tips'),
    {
      confirmButtonText: $t('crud.filter.submitBtn'),
      cancelButtonText: $t('crud.filter.cancelBtn'),
      type: 'warning'
    }
  ).then(() => {
    http({
      url: http.adornUrl('/prod/prod'),
      method: 'delete',
      data: http.adornData(ids, false)
    }).then(() => {
      page.total = page.total - ids.length
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          refreshChange()
        }
      })
    })
  })
}

/**
 * 搜索
 */
const onSearch = (newData = false) => {
  getDataList(page, newData)
}
/**
 * 重置表单
 */
const searchFormRef = ref()
const onResetSearch = () => {
  searchFormRef.value.resetFields()
  prodName.value = ''
  prodId.value = null
}

// 刷新回调
const refreshChange = () => {
  dataListSelections.value = []
  getDataList(page)
}

// 跳转至导入选择
const getWaitingConsignmentExcel = () => {
  getDataList(page)
}

// ['普通商品', '团购商品', '秒杀商品']
const shopProdTypeArr = ref([
  $t('product.ordProd'),
  $t('product.groupingProd'),
  $t('product.spikeProd')
])
</script>

<style lang="scss" scoped>
.page-prod-manage{
  .operation-bar {
    .batch-setting-con {
      margin-left: 10px;
    }
  }
  .water-sold-con {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.popover-box {
  position: relative;
  display: flex;
  flex-direction: column;
  :deep(.el-input-number) {
    width: 130px;
  }
  .popover-bottom {
    flex: 1;
    display: flex;
    justify-content: center;
    margin-top: 10px;
  }
}
</style>
